var Md5 = require('../utils/md5.js');
const formatTime = date => {
	var date=new Date();
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
const formatDate = date => {
	var date = new Date();
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()
	const hour = date.getHours()
	const minute = date.getMinutes()
	const second = date.getSeconds()

	return [year, month, day].map(formatNumber).join('-') 
}
const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}

function http(url, data, callback) {
    data.key = getApp().globalData !== undefined ? getApp().globalData.key : '';
    // data.key = wx.getStorageSync('key') !== undefined ? wx.getStorageSync('key') : '';
    data.timestamp = Date.parse(new Date()) / 1000;
    var sign = Md5.hexMD5(data.timestamp + 'iqidian' + data.key); //md5加密
    data.sign = sign;
    if (data.goods_list !== undefined) {
        data.goods_list = JSON.stringify(data.goods_list);
    }
    wx.request({
        url: getApp().globalData.http + url,
        data: data,
        header: {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        method: "POST",
        dataType: "json",
        success: function(res) {
            callback(res.data)
        },
        fail: function(res) {},
        complete: function(res) {},
    })
};

function message(msg) {
    wx.showModal({
        title: '温馨提示',
        content: msg,
        showCancel: false,
        success(res) {}
    })
}

function showLoading(msg) {
    wx.showLoading({
        mask: true,
        title: msg ? msg : '加载中',
    })
}

function hideLoading() {
    wx.hideLoading();
}
function showSuccess(msg, icon, mask, time) {
	icon = icon ? icon.toString() : 'success';
	mask = mask === false || mask === true ? mask : true;
	wx.showToast({
		title: msg ? msg : '成功',
		icon: icon,
		mask: mask,
		duration: time ? time : 2000,
	});
}
function getJson(url) {
	var arr = url.split('?')[1].split('&')
	var theRequest = new Object();
	for (var i = 0; i < arr.length; i++) {
		var kye = arr[i].split("=")[0]
		var value = arr[i].split("=")[1]
		// 给对象赋值
		theRequest[kye] = value
	}
	return theRequest;
}

module.exports = {
    formatTime: formatTime,
    http: http,
    message: message,
    showLoading: showLoading,
    hideLoading: hideLoading,
	showSuccess: showSuccess,
	formatDate: formatDate,
	getJson: getJson
}